package pers.mingshan.thread;

import org.junit.Test;

/**
 * @author hanjuntao
 * @date 2025/9/9 0009
 */
public class SafeThreadStop implements Runnable {
    private volatile boolean running = true;

    @Override
    public void run() {
        while (running) {
            try {
                // 执行任务
                System.out.println("当前时间：" + new java.util.Date() + "-线程运行中...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // 响应中断请求
                System.out.println("当前时间：" + new java.util.Date() + "-线程被中断，正在清理资源...");
                Thread.currentThread().interrupt(); // 重新设置中断状态
                break;
            }
        }
        System.out.println("当前时间：" + new java.util.Date() + "-线程安全退出");
    }

    public void stop() {
        System.out.println("当前时间：" + new java.util.Date() + "-running标志设置为false");
        running = false;
    }


    /**
     * 手动设置标志位
     *
     * @throws InterruptedException
     */
    @Test
    public void test1() throws InterruptedException {
        SafeThreadStop task = new SafeThreadStop();
        Thread thread = new Thread(task);
        thread.start();

        // 运行3秒后请求停止
        Thread.sleep(3000);
        task.stop();

        // 等待线程结束
        thread.join(); // 添加这行代码等待线程结束

        System.out.println("当前时间：" + new java.util.Date() + "-测试方法结束");
    }

    /**
     * 使用interrupt()方法
     *
     * @throws InterruptedException
     */
    @Test
    public void test2() throws InterruptedException {
        SafeThreadStop task = new SafeThreadStop();
        Thread thread = new Thread(task);
        thread.start();

        // 运行3秒后请求停止
        Thread.sleep(3000);
        thread.interrupt(); // 如果线程在阻塞状态，这会唤醒它

        // 等待线程结束
        thread.join(); // 添加这行代码等待线程结束

        System.out.println("当前时间：" + new java.util.Date() + "-测试方法结束");
    }

}